import os
import time
import random
import shutil
import xgboost as xgb
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from flask import Flask, request, jsonify
from sklearn.model_selection import train_test_split
from config import OUTPUT_XGB_PATH

app = Flask(__name__)

# **字体设置**
if os.name == "nt":  # Windows
    print("正在使用 Windows 环境...")
    plt.rcParams["font.family"] = "SimHei"
elif os.name == "posix":  # Linux
    print("正在使用 Linux 环境...")
    font_path = "/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc"
    if os.path.exists(font_path):
        my_font = fm.FontProperties(fname=font_path)
        plt.rcParams["font.family"] = my_font.get_name()
    else:
        print("⚠️ [警告] 未找到 wqy-zenhei，使用 DejaVu Sans 作为备用字体！")
        plt.rcParams["font.family"] = "DejaVu Sans"

plt.rcParams['axes.unicode_minus'] = False

# **清除 Matplotlib 缓存**
matplotlib_cache = os.path.expanduser("~/.cache/matplotlib")
if os.path.exists(matplotlib_cache):
    shutil.rmtree(matplotlib_cache)
    print("✅ Matplotlib 字体缓存已清除，确保字体设置生效。")


def plot_feature_importance(xlsx_file, select_feature, target_feature):
    """
    计算并绘制 XGBoost 特征重要性图，并返回相关信息。

    参数：
    - xlsx_file: Excel 数据文件路径
    - select_feature: 选取的特征列名称列表
    - target_feature: 目标列名称

    返回：
    - output_file_path: 生成的特征重要性图片路径
    - sorted_importance: 排序后的特征重要性字典
    """
    try:
        # **读取 Excel 数据**
        df = pd.read_excel(xlsx_file)
        X = df[select_feature]  # 选择特征
        y = df[target_feature]  # 目标变量
    except Exception as e:
        raise ValueError(f"读取 Excel 文件失败: {str(e)}")

    # **拆分训练集和测试集**
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

    # **训练 XGBoost 回归模型**
    try:
        model = xgb.XGBRegressor()
        model.fit(X_train, y_train)
    except Exception as e:
        raise ValueError(f"XGBoost 训练失败: {str(e)}")

    # **获取特征重要性（基于特征在树中的使用次数）**
    importance = model.get_booster().get_score(importance_type='weight')

    # **按重要性排序**
    sorted_importance = sorted(importance.items(), key=lambda x: x[1], reverse=True)

    # **确保输出目录存在**
    output_dir = OUTPUT_XGB_PATH  # ✅ 使用 config 里面的路径
    os.makedirs(output_dir, exist_ok=True)

    # **生成文件名（时间戳 + 随机数）**
    timestamp = int(time.time() * 1000)
    random_number = random.randint(1000, 9999)
    output_file_name = f"feature_importance_{timestamp}_{random_number}.png"
    output_file_path = os.path.join(output_dir, output_file_name)

    # **绘制特征重要性**
    xgb.plot_importance(model, importance_type='weight', max_num_features=10)
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig(output_file_path)
    plt.close()

    print(f"✅ 特征重要性图已保存为: {output_file_path}")

    return output_file_path, sorted_importance
